<?php
/**
 * 门店自提发货单处理Lib类
 * 
 * @author: wangbiao@shopex.cn
 */
class wap_delivery
{
    function __construct($app)
    {
        $this->app = $app;
    }

    /**
     * 通过外部发货单号找到关联的订单号
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return Array
     */
    public function getList($filter, $offset=0, $limit=2, $orderby='')
    {
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        $ordersObj         = app::get('ome')->model('orders');
        
        //门店订单的配送超时时间
        if($filter['branch_id'])
        {
            $storeObj       = app::get('o2o')->model('store');
            $storeInfo      = $storeObj->dump(array('branch_id'=>$filter['branch_id']), 'store_id');
        }
        
        //发货单列表
        $fields            = 'delivery_id, delivery_bn, itemNum, status, print_status, process_status, is_received, shop_id, 
                              outer_delivery_bn, ship_name, ship_area, ship_addr, ship_mobile, ship_tel, 
                              branch_id, confirm, is_cod, order_bn, total_amount, logi_name, create_time';
        $dataList          = $wapDeliveryObj->getList($fields, $filter, $offset, $limit, $orderby);
        foreach ($dataList as $key => $val)
        {
            #订单信息
            $dataList[$key]['order_info']    = $ordersObj->dump(array('order_bn'=>$val['order_bn']), 'order_id,createtime, mark_text, is_tax, tax_company, paytime');
            if($dataList[$key]['order_info']['mark_text']) {
                $mark_text    = unserialize($dataList[$key]['order_info']['mark_text']);
                if ($mark_text) {
                    foreach ($mark_text as $k=>$v) {
                        if (!strstr($v['op_time'], "-"))
                        {
                            $v['op_time']    = date('Y-m-d H:i:s',$v['op_time']);
                            $mark_text[$k]['op_time']    = $v['op_time'];
                        }
                    }
                }
                $dataList[$key]['order_info']['mark_text']    = $mark_text;
            }
            
            #发货单明细
            if($val['outer_delivery_bn'])
            {
                $count_num    = 0;
                $dataList[$key]['delivery_items']    = $this->getDeliveryItemList($val['outer_delivery_bn']);
                $dataList[$key]['dlyItemCount']      = $count_num;
            }
            $dataList[$key]['dly_status']    = $this->formatDeliveryStatus('status', $val['status']);
            $dataList[$key]['dly_confirm']   = $this->formatDeliveryStatus('confirm', $val['confirm']);
            
            #已签收
            if($val['status']=='3' && $val['is_received']=='2')
            {
                $dataList[$key]['dly_status']    = '已签收';
            }
            
            #门店自提仓库对应店铺信息
            $dataList[$key]['shop_info']     = $this->getBranchShopInfo($val['branch_id']);
            
            #付款方式
            $dataList[$key]['pay_name']    = ($val['is_cod']=='true' ? '货到付款' : '款到发货');

            if ($val['is_cod'] == 'true') {

                $dataList[$key]['order_extends'] = app::get('ome')->model('order_extend')->dump(array('order_id'=>$dataList[$key]['order_info']['order_id']), '*');
            }

            #履约超时时间
            $dataList[$key]['dly_overtime']    = $this->getDeliveryOvertime($val['create_time']);
        }

        unset($filter, $fields, $count_num, $storeInfo, $mark_text);
        
        return $dataList;
    }
    
    /**
     * 通过外部发货单号找到关联的订单号
     * 
     * @param $outer_delivery_bn    ome发货单号
     * @return Array
     */
    public function getDeliverBnByOrderId($outer_delivery_bn)
    {
        $deliveryObj    = app::get('ome')->model('delivery');
        
        $sql            = "SELECT dord.order_id FROM sdb_ome_delivery_order AS dord 
                           LEFT JOIN sdb_ome_delivery AS d ON(dord.delivery_id=d.delivery_id)
                           WHERE d.delivery_bn='". $outer_delivery_bn ."' AND (d.parent_id=0 OR d.is_bind='true') AND d.disabled='false' 
                           AND d.status NOT IN('failed','cancel','back','return_back')";
        $order_ids      = $deliveryObj->db->selectrow($sql);
        
        return $order_ids['order_id'];
    }
    
    /**
     * 通过外部发货单号找到ome发货单号详细信息
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $delivery_bn
     */
    public function getOmeDeliveryInfo($outer_delivery_bn)
    {
        $deliveryObj    = app::get('ome')->model('delivery');
        
        $sql            = "SELECT delivery_id, delivery_bn FROM sdb_ome_delivery WHERE delivery_bn='". $outer_delivery_bn ."' 
                           AND (parent_id=0 OR is_bind='true') AND disabled='false' AND status NOT IN('failed','cancel','back','return_back')";
        $delivery_info  = $deliveryObj->db->selectrow($sql);
        
        return $delivery_info;
    }
    
    /**
     * 通过外部发货单号找到订单详细信息
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $orderInfo
     */
    public function getDeliverBnByOrderInfo($outer_delivery_bn)
    {
        $ordersObj         = app::get('ome')->model('orders');
        
        $order_id    = $this->getDeliverBnByOrderId($outer_delivery_bn);
        if(empty($order_id))
        {
            return '';
        }
        
        $orerInfo    = $ordersObj->dump(array('order_id'=>$order_id), 'order_id, order_bn, process_status, pay_status, ship_status');
        return $orerInfo;
    }
    
    /**
     * Wap发货单状态
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $orderInfo
     */
    public function formatDeliveryStatus($type='', $suffix='')
    {
        $data    = array();
        
        $data['status']          = array('处理中', '取消', '暂停', '已发货');
        $data['print_status']    = array('未打印', '已打印');
        $data['process_status']  = array('未打印', '已打印', '已校验', 4=>'已称重打包', 8=>'已物流交接');
        $data['confirm']         = array(1=>'已确认', 2=>'已拒绝', 3=>'未确认');
        $data['is_cod']         = array("true"=>'货到付款', "false"=>'款到发货');
        
        if($type)
        {
            return $suffix || $suffix === '0' ? $data[$type][$suffix] : $data[$type];
        }
        
        return $data;
    }
    
    /**
     * 通过门店自提仓库获取店铺详细信息
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $orderInfo
     */
    public function getBranchShopInfo($branch_id)
    {
        //$oBranchObj     = app::get('ome')->model('branch');

        $storeObj    = app::get('o2o')->model('store');

        $branch_info    = $storeObj->db->selectrow("SELECT branch_id, wms_id, branch_bn, name FROM sdb_ome_branch WHERE branch_id=" . $branch_id);
        
        $storeInfo    = array();
        if($branch_info)
        {
            $branch_info['branch_name']    = $branch_info['name'];
            unset($branch_info['name']);

            $storeInfo = $storeObj->dump(array('branch_id'=>$branch_info['branch_id']),'store_id, store_bn, name, area, shop_id, addr, contacter, mobile, tel');


            $storeInfo['store_name']    = $storeInfo['name'];
            $area    = explode(':', $storeInfo['area']);
            $storeInfo['store_addr']    = str_replace('/', '-', $area[1]) . $storeInfo['addr'];
            unset($storeInfo['name']);
        }
        
        return array_merge($branch_info, $storeInfo);
    }
    
    /**
     * 获取订单明细列表
     * 
     * @param int $order_id 订单id
     * @param bool $sort 是否要排序，默认不要。排序后的结果会按照普通商品、捆绑商品、赠品、配件等排列
     */
    function getOrderItemList($order_id, $sort=false)
    {
        $oOrder        = app::get('ome')->model('orders');
        $order_items   = array();
        
        if($sort)
        {
            $items    = $oOrder->dump($order_id, 'order_id', array("order_objects"=>array("*")));
            foreach($items['order_objects'] as $k=>$v)
            {
                $order_items[$v['obj_type']][$k] = $v;
                
                $sql    = "SELECT *,nums AS quantity FROM sdb_ome_order_items WHERE obj_id=".$v['obj_id']." AND item_type='product' ORDER BY item_type";
                foreach($oOrder->db->select($sql) as $it)
                {
                    $order_items[$v['obj_type']][$k]['order_items'][$it['item_id']] = $it;
                }
                
                $sql    = "SELECT *,nums AS quantity FROM sdb_ome_order_items WHERE obj_id=".$v['obj_id']." AND item_type<>'product' ORDER BY item_type";
                foreach($oOrder->db->select($sql) as $it)
                {
                    $order_items[$v['obj_type']][$k]['order_items'][$it['item_id']] = $it;
                }
            }
        }
        else 
        {
            $items    = $oOrder->dump($order_id, 'order_id', array("order_objects"=>array("*",array("order_items"=>array("*")))));
            foreach($items['order_objects'] as $oneobj)
            {
                foreach ($oneobj['order_items'] as $objitems)
                    $order_items[] = $objitems;
            }
        }
        
        return $order_items;
    }
    
    /**
     * 获取发货单明细
     */
    function getDeliveryItemList($delivery_bn, $offset=0, $limit=-1)
    {
        $basicMaterialObj = app::get('material')->model('basic_material');
        $deliveryObj   = app::get('ome')->model('delivery');
        $dlyItemObj    = app::get('ome')->model('delivery_items');
        
        $deliveryInfo    = $deliveryObj->dump(array('delivery_bn'=>$delivery_bn), 'delivery_id');
        if(empty($deliveryInfo))
        {
            return '';
        }
        
        $delivery_id   = $deliveryInfo['delivery_id'];
        $items         = $dlyItemObj->getList('*', array('delivery_id' => $delivery_id), 0, -1);
        
        if ($items)
        {
            foreach ($items as $key => $item)
            {
                //将商品的显示名称改为后台的显示名称
                $productInfo= $basicMaterialObj->dump(array('material_bn'=>$items[$key]['bn']), 'material_name');
                
                $items[$key]['product_name'] = $productInfo['material_name'];
            }
        }
        
        return $items;
    }
    
    /**
     * 获取履约超时时间
     * 
     * @param $delivery_time 发货时间
     */
    function getDeliveryOvertime($delivery_time)
    {
        //履约超时时间设置(分钟)
        $minute    = app::get('o2o')->getConf('o2o.delivery.dly_overtime');
        $minute    = intval($minute);
        
        if(empty($minute) || empty($delivery_time))
        {
            return false;
        }
        
        $second    = $minute * 60;
        
        //履约超时时间
        $diff_time    = time() - $delivery_time;
        
        return ($diff_time > $second ? $diff_time : 0);
    }
    
    /**
     * 读取缓存数据
     * 
     */
    function fetchDataFromCache()
    {
        $branchObj     = kernel::single('o2o_store_branch');
        $branch_ids    = $branchObj->getO2OBranchByUser(true);
        if(empty($branch_ids))
        {
            return false;
        }
        $branch_id    = $branch_ids[0];
        
        $statistic    = cachecore::fetch('wap_statistic_'. $branch_id);
        
        //更新今日订单总数(15分钟更新一次)
        if($statistic)
        {
            $today_order    = cachecore::fetch('wap_today_order_'. $branch_id);
            if(empty($today_order))
            {
                $this->taskmgr_statistic('today');
                
                cachecore::store('wap_today_order_'. $branch_id, '1', 900);
                
                //重新读取数据
                $statistic    = cachecore::fetch('wap_statistic_'. $branch_id);
            }
        }
        
        return $statistic;
    }
    
    /**
     * 任务列表执行统计订单数据
     */
    function taskmgr_statistic($type)
    {
        $branchObj     = kernel::single('o2o_store_branch');
        $branch_ids    = $branchObj->getO2OBranchByUser(true);
        $branch_id     = $branch_ids[0];
        
        if(empty($branch_id) || empty($type))
        {
            return false;
        }
        
        //任务队列
        $push_params = array(
                'data' => array(
                        'branch_id' => $branch_id,
                        'type' => $type,
                        'task_type' => 'autowapdly',
                ),
                'url' => kernel::openapi_url('openapi.autotask','service')
        );
        kernel::single('taskmgr_interface_connecter')->push($push_params);
        
        return true;
    }
}
